#! /usr/bin/env python
#
"""Poor man's substitute for "pickle", supporting Cython classes.
"""
__docformat__ = 'reStructuredText'


import os


cdef list load(filename):
    cdef list result
    cdef object checkpoint_file
    cdef object error

    try:
        checkpoint_file = open(filename, 'r')
        result = [ eval(line) for line in checkpoint_file ]
        return result
    except IOError, error:
        if error.errno == 2: # No such file or directory
            return None
        else:
            raise error
        

cdef void save(list items, filename):
    cdef object checkpoint_file

    try:
        checkpoint_file = open(filename, 'w')
        for item in items:
            checkpoint_file.write("%s\n" % repr(item))
    except Exception, error:
        # remove file to avoid corrupted restart
        os.remove(filename)
        raise error



## main: run tests

if "__main__" == __name__:
    import doctest
    doctest.testmod(name="loadsave",
                    optionflags=doctest.NORMALIZE_WHITESPACE)
